package com.thinksns.sociax.t4.android.setting;

import org.json.JSONObject;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.CheckBox;
import android.widget.CheckedTextView;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.thinksns.sociax.api.Api;
import com.thinksns.sociax.component.CustomTitle;
import com.thinksns.sociax.component.LeftAndRightTitle;
import com.thinksns.sociax.t4.android.ThinksnsAbscractActivity;
import com.thinksns.sociax.android.R;
import com.thinksns.sociax.t4.android.video.PreferenceUtils;
import com.thinksns.sociax.t4.android.video.ToastUtils;
import com.thinksns.sociax.t4.unit.UnitSociax;
import com.thinksns.sociax.thinksnsbase.utils.LogFactory;
import com.thinksns.sociax.thinksnsbase.utils.PrefUtils;

/**
 * 类说明：隐私设置类
 *
 * @author wz
 * @version 1.0
 * @date 2014-9-4
 * @date 20125-7-2 caoligai 修改 将按下 back 键退出并保存数据修改为每修改一个数据就保存，按下 back 时直接 finish()
 */
public class ActivityManagePrivacy extends ThinksnsAbscractActivity {
    protected static final int GET_PRIVACY = 5;
    protected static final int SAVE_PRIVACY = 4;
    private Handler handler;
    private CheckBox tv_comment_all, tv_comment_follow, tv_message_all,
            tv_message_follow, tv_space_all, tv_space_follow;
    private String[] oldprivacy = new String[3], newprivacy = new String[3];
    private String space = "", comment = "", message = "";

    //4.5版本隐私设置修改,增加其他设置
    private RelativeLayout rl_all_message, rl_follow_message, rl_allcomment, rl_follow_comment, rl_all_zone, rl_follow_zone;
    private CheckedTextView mCTV_Auto_Location; // 分享自动定位开关 ，默认开启
    private RadioGroup mRG_Auto_Clear_Cache; // 自动清除缓存周期（日/周/月/从不）默认从不
    //修改中，对应的按钮不可点击(参照IOS) By Catherine
    private boolean isChangeComment;
    private boolean isChangeMessage;
    private boolean isChangeZone;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initIntentData();
        initView();
        initListener();
        initData();
    }

    /**
     * 载入数据
     */
    private void initData() {
        new Thread(new Runnable() {

            @Override
            public void run() {

                Message msg = handler.obtainMessage();
                msg.what = GET_PRIVACY;
                msg.obj = new Api.Oauth().getPrivacy();
                handler.sendMessage(msg);
            }
        }).start();
        mCTV_Auto_Location.setChecked(PreferenceUtils.getAutoLocation());
        if (PreferenceUtils.getAutoClearCacheId() == 0){
            mRG_Auto_Clear_Cache.check(R.id.rb_never);
        }else{
            mRG_Auto_Clear_Cache.check(PreferenceUtils.getAutoClearCacheId());
        }
    }

    /**
     * 初始化监事件
     */
    private void initListener() {

        //4.5版本隐私设置修改
        rl_allcomment.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                //先判断网络是否异常
                if (!UnitSociax.isNetWorkON(rl_allcomment.getContext())) {
                    Toast.makeText(rl_allcomment.getContext(), getResources().getString(R.string.net_work_error),
                            Toast.LENGTH_SHORT).show();
                    return;
                }
                //修改中或者当前已选中，不可操作
                if (!isChangeComment && !tv_comment_all.isChecked()) {
                    isChangeComment = true;
                    comment = "0";
                    changePrivate();
                } else {
                    //目前不知道是否要提示，看胡主管
                }

            }
        });
        rl_follow_comment.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                if (!UnitSociax.isNetWorkON(rl_allcomment.getContext())) {
                    Toast.makeText(rl_allcomment.getContext(), getResources().getString(R.string.net_work_error),
                            Toast.LENGTH_SHORT).show();
                    return;
                }
                if (!isChangeComment && !tv_comment_follow.isChecked()) {
                    isChangeComment = true;
                    comment = "1";
                    changePrivate();
                }

            }
        });

        rl_all_message.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                if (!UnitSociax.isNetWorkON(rl_allcomment.getContext())) {
                    Toast.makeText(rl_allcomment.getContext(), getResources().getString(R.string.net_work_error),
                            Toast.LENGTH_SHORT).show();
                    return;
                }
                if (!isChangeMessage && !tv_message_all.isChecked()) {
                    isChangeMessage = true;
                    message = "0";
                    changePrivate();
                }

            }
        });
        rl_follow_message.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                if (!UnitSociax.isNetWorkON(rl_allcomment.getContext())) {
                    Toast.makeText(rl_allcomment.getContext(), getResources().getString(R.string.net_work_error),
                            Toast.LENGTH_SHORT).show();
                    return;
                }
                if (!isChangeMessage && !tv_message_follow.isChecked()) {
                    isChangeMessage = true;
                    message = "1";
                    changePrivate();
                }

            }
        });

        rl_all_zone.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                if (!UnitSociax.isNetWorkON(rl_allcomment.getContext())) {
                    Toast.makeText(rl_allcomment.getContext(), getResources().getString(R.string.net_work_error),
                            Toast.LENGTH_SHORT).show();
                    return;
                }
                if (!isChangeZone && !tv_space_all.isChecked()) {
                    isChangeZone = true;
                    space = "0";
                    changePrivate();
                }

            }
        });
        rl_follow_zone.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                if (!UnitSociax.isNetWorkON(rl_allcomment.getContext())) {
                    Toast.makeText(rl_allcomment.getContext(), getResources().getString(R.string.net_work_error),
                            Toast.LENGTH_SHORT).show();
                    return;
                }
                if (!isChangeZone && !tv_space_follow.isChecked()) {
                    isChangeZone = true;
                    space = "1";
                    changePrivate();
                }

            }
        });
        mCTV_Auto_Location.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                mCTV_Auto_Location.toggle();
                PreferenceUtils.saveAutoLocation(mCTV_Auto_Location.isChecked());
            }
        });
        mRG_Auto_Clear_Cache.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                PreferenceUtils.saveAutoClearCacheId(checkedId);
            }
        });
    }

    protected void savePrivateTask(final String[] newpriv) {
        new Thread(new Runnable() {

            @Override
            public void run() {
                Message msg = handler.obtainMessage();
                msg.what = SAVE_PRIVACY;
                msg.obj = new Api.Oauth().savePrivacy(newpriv);
                handler.sendMessage(msg);
            }
        }).start();
    }

    /**
     * 修改选中状态并向服务器发送请求
     *
     * @auther Catherine
     * @date 2016 11 25
     */
    private void changePrivate() {
        newprivacy[0] = space;
        newprivacy[1] = comment;
        newprivacy[2] = message;
        savePrivateTask(newprivacy);
    }

    /**
     * 设置权限数据、UI
     *
     * @auther Catherine
     * @date 2016 11 25
     */
    private void setPrivate() {

        newprivacy[0] = space;
        newprivacy[1] = comment;
        newprivacy[2] = message;
        if (isChangeComment) {
            isChangeComment = false;
        }
        if (isChangeMessage) {
            isChangeMessage = false;
        }
        if (isChangeZone) {
            isChangeZone = false;
        }

        if ((space + "").equals("1")) {
            tv_space_all.setChecked(false);
            tv_space_follow.setChecked(true);
        } else {
            tv_space_all.setChecked(true);
            tv_space_follow.setChecked(false);
        }

        if ((comment + "").equals("1")) {
            tv_comment_all.setChecked(false);
            tv_comment_follow.setChecked(true);

        } else {
            tv_comment_all.setChecked(true);
            tv_comment_follow.setChecked(false);
        }

        if ((message + "").equals("1")) {
            tv_message_all.setChecked(false);
            tv_message_follow.setChecked(true);
        } else {
            tv_message_all.setChecked(true);
            tv_message_follow.setChecked(false);
        }
    }

    /**
     * 初始化intent信息
     */
    private void initIntentData() {
    }

    /**
     * 初始化页面
     */
    private void initView() {
        tv_comment_all = (CheckBox) findViewById(R.id.tv_comment_all);
        tv_comment_follow = (CheckBox) findViewById(R.id.tv_comment_follow);

        tv_space_all = (CheckBox) findViewById(R.id.tv_space_all);
        tv_space_follow = (CheckBox) findViewById(R.id.tv_space_follow);

        tv_message_all = (CheckBox) findViewById(R.id.tv_sixin_all);
        tv_message_follow = (CheckBox) findViewById(R.id.tv_sixin_follow);

        //4.5版本隐私设置修改
        rl_all_message = (RelativeLayout) findViewById(R.id.RelativeLayout01);
        rl_follow_message = (RelativeLayout) findViewById(R.id.RelativeLayout03);
        rl_allcomment = (RelativeLayout) findViewById(R.id.ll_re_pass);
        rl_follow_comment = (RelativeLayout) findViewById(R.id.rl_pravicy_manage);
        rl_all_zone = (RelativeLayout) findViewById(R.id.RelativeLayout04);
        rl_follow_zone = (RelativeLayout) findViewById(R.id.RelativeLayout06);
        mCTV_Auto_Location = (CheckedTextView) findViewById(R.id.ctv_auto_location);
        mRG_Auto_Clear_Cache = (RadioGroup) findViewById(R.id.rg_clear_cache);
        handler = new Handler() {
            /**
             *
             * @param msg
             */
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case GET_PRIVACY:
                        try {

                            JSONObject result2json = new JSONObject(msg.obj.toString());

                            space = result2json.getString("space");
                            comment = result2json.getString("comment_weibo");
                            message = result2json.getString("message");

                            oldprivacy[0] = space;
                            oldprivacy[1] = comment;
                            oldprivacy[2] = message;

                            setPrivate();

                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        break;
                    case SAVE_PRIVACY:
                        try {
                            JSONObject result2json = new JSONObject(msg.obj.toString());
                            LogFactory.createLog("ActivityManagePrivacy").d("change result //"+result2json.toString());
                            String result = result2json.getString("status");
                            //修改提示为统一提示-By Catherine 11.25
                            String msgAlert = result2json.getString("msg");
                            if (!TextUtils.isEmpty(result) && result.equals("1")) {
                                JSONObject data = result2json.getJSONObject("data");
                                space = data.getString("space");
                                comment = data.getString("comment_weibo");
                                message = data.getString("message");
                                setPrivate();
                            } else {
                                //修改失败，则重置状态并且提示
                                Toast.makeText(getApplicationContext(), msgAlert, Toast.LENGTH_SHORT).show();
                                if (isChangeComment) {
                                    comment = (comment.equals("1")) ? "0" : "1";
                                }
                                if (isChangeMessage) {
                                    message = (message.equals("1")) ? "0" : "1";
                                }
                                if (isChangeZone) {
                                    space = (space.equals("1")) ? "0" : "1";
                                }
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            LogFactory.createLog("ActivityManagePrivacy").e("parse data error"+e.toString());
                        }
                        if (isChangeComment) {
                            isChangeComment = false;
                        }
                        if (isChangeMessage) {
                            isChangeMessage = false;
                        }
                        if (isChangeZone) {
                            isChangeZone = false;
                        }
                        break;
                }
            }

            ;
        };
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    public String getTitleCenter() {
        return "隐私设置";
    }

    @Override
    protected CustomTitle setCustomTitle() {
        return new LeftAndRightTitle(R.drawable.img_back, this);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_privacy;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {

			/*newprivacy[0] = space;
            newprivacy[1] = comment;
			newprivacy[2] = message;
			if (space.equals(oldprivacy[0]) && comment.equals(oldprivacy[1])
					&& message.equals(oldprivacy[2])) {
				finish();
			} else {
				savePrivateTask();
			}*/
            finish();
        }
        return super.onKeyDown(keyCode, event);
    }
}
